package cn.shop.front.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.collection.CollectionUtil;
import cn.shop.front.service.CartService;
import cn.shop.front.util.AliasUtil;
import cn.shop.front.util.CurrentUserUtil;
import cn.shop.transcation.order.entity.CertQueryReq;
import cn.shop.utils.ApiResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 购物车相关接口
 *
 * @author : 李一涵
 * @date : Created in 2022/5/23 10:16
 * @description :
 */
@SaCheckLogin
@RestController
@RequestMapping("/api/v1/cart")
public class CartController {

    @Resource
    private CartService cartService;

    /**
     * 获取购物车所有商品编号
     *
     * @return 返回结果
     */
    @GetMapping("/ids")
    public ApiResult<List<Long>> cartOrders(HttpServletRequest request) {
        long uid = CurrentUserUtil.getUserId();
        String domain = AliasUtil.getAlias(request);
        if (uid == 0) {
            return ApiResult.success(Collections.emptyList());
        }
        return ApiResult.success(cartService.cartOrders(uid, domain));
    }

    /**
     * 分页查询
     *
     * @param req 查询条件
     * @return 返回结果
     */
    @GetMapping("")
    public ApiResult<Map<String, Object>> list(CertQueryReq req, HttpServletRequest request) {
        long uid = CurrentUserUtil.getUserId();
        String domain = AliasUtil.getAlias(request);
        if (uid == 0) {
            return ApiResult.success();
        }
        req.setUserId(uid);
        return ApiResult.success(cartService.carts(req, domain));
    }

    /**
     * 保存到购物车
     *
     * @param orderIds 订单编号列表
     * @return 返回结果
     */
    @PostMapping("")
    public ApiResult<Map<String, Object>> save(@RequestBody List<Long> orderIds, HttpServletRequest request) {
        long uid = CurrentUserUtil.getUserId();
        String domain = AliasUtil.getAlias(request);
        if (uid == 0) {
            return ApiResult.success();
        }
        List<Long> ids = cartService.cartOrders(uid, domain);
        orderIds = orderIds.stream().filter(id -> !ids.contains(id)).collect(Collectors.toList());
        if (orderIds.isEmpty()) {
            return ApiResult.fail("所选订单已经在购物车内");
        }
        return ApiResult.result(cartService.saveCarts(orderIds, uid, domain));
    }

    /**
     * 从购物车删除
     *
     * @param ids 购物车编号
     * @return 返回结果
     */
    @PostMapping("/delete")
    public ApiResult<Map<String, Object>> delete(@RequestBody List<Long> ids) {
        long uid = CurrentUserUtil.getUserId();
        if (uid == 0) {
            return ApiResult.success();
        }
        return ApiResult.result(cartService.deleteCarts(ids));
    }
}
